package com.liugai.lgeachday.tool;

import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;

public class EntityTool {

    public static Example generateExample(Object obj, String condition, Object conditionValue) throws IllegalAccessException {
        if (obj == null) {
            return null;
        }
        Example example = new Example(obj.getClass());
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        boolean isCondition = false;
        if (condition != null) {
            if (conditionValue != null) {
                example.createCriteria().andCondition(condition, conditionValue);
            }
            else  {
                example.createCriteria().andCondition(condition);
            }
            isCondition = true;
        }
        for(Field field: declaredFields) {
            field.setAccessible(true);
            Object fieldValue = field.get(obj);
            int modifiers = field.getModifiers();
            if (fieldValue != null && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
                example.createCriteria().andEqualTo(field.getName(),fieldValue);
            }
        }
        return example;

    }
}
